<template>
  <view :class="['container', `theme-${currentTheme}`]">
    <form @submit.prevent="handleSubmit">
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="section-title">基本信息</view>
        
        <view class="form-item">
          <text class="label">姓名</text>
          <input 
            type="text" 
            v-model="formData.name" 
            placeholder="请输入姓名"
            class="input"
            @blur="checkNameExists"
          />
          <text v-if="nameExists" class="error-tip">该姓名已存在</text>
        </view>
        
        <view class="form-item">
          <text class="label">关系</text>
          <input 
            type="text" 
            v-model="formData.relation" 
            placeholder="请输入关系"
            class="input"
          />
        </view>

        <view class="form-item">
          <text class="label">分类</text>
          <input 
            type="text" 
            v-model="formData.category" 
            placeholder="请输入分类"
            class="input"
          />
        </view>
      </view>

      <!-- 备注信息 -->
      <view class="form-section">
        <view class="section-title">备注信息</view>
        
        <view class="form-item">
          <text class="label">备注</text>
          <textarea 
            v-model="formData.notes" 
            placeholder="请输入备注信息"
            class="textarea"
          />
        </view>
      </view>
      
      <!-- 隐私说明 -->
      <view class="privacy-notice">
        <text class="privacy-text">点击"保存"即表示您同意我们在本地存储您提供的信息，仅用于宴禧录记录管理功能的使用。</text>
        <view class="privacy-link-wrap" @tap="showPrivacyPolicy">
          <text class="privacy-link">《查看隐私政策》</text>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn">
        <button 
          form-type="submit" 
          class="btn"
          :disabled="loading || nameExists"
        >
          {{ loading ? '保存中...' : '保存' }}
        </button>
      </view>
    </form>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useContactStore } from '@/store/modules/contact';
import { useThemeStore } from '@/store/modules/theme';
import { Contact } from '@/types';
import useThemeMixin from '@/mixins/themeMixin';

const contactStore = useContactStore();
const themeStore = useThemeStore();

// 使用主题混入，实现导航栏颜色与主题同步
useThemeMixin();

const loading = ref(false);
const contactId = ref<string | null>(null);
const nameExists = ref(false);

// 获取当前主题
const currentTheme = computed(() => {
  return themeStore.currentTheme;
});

// 表单数据
const formData = ref<Partial<Contact> & { relation?: string }>({
  name: '',
  category: '',
  notes: '',
  relation: ''
});

// 显示隐私政策
const showPrivacyPolicy = () => {
  console.log('跳转到隐私政策页面');
  
  // 导航到隐私政策页面
  uni.navigateTo({
    url: '/pages/settings/privacy'
  });
};

// 检查姓名是否已存在
const checkNameExists = () => {
  if (!formData.value.name) return;
  
  // 如果是编辑模式则排除当前联系人
  const existingContact = contactStore.getAllContacts.find((contact: Contact) => 
    contact.name === formData.value.name && 
    (!contactId.value || contact.id !== contactId.value)
  );
  
  nameExists.value = !!existingContact;
};

// 表单提交
const handleSubmit = async () => {
  console.log('提交表单...');
  
  if (!formData.value.name) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    });
    return;
  }

  // 再次验证姓名是否存在
  checkNameExists();
  if (nameExists.value) {
    uni.showToast({
      title: '该姓名已存在',
      icon: 'none'
    });
    return;
  }

  // 检查是否同意隐私政策
  try {
    const hasAgreed = uni.getStorageSync('privacyPolicyAgreed');
    if (!hasAgreed) {
      uni.showToast({
        title: '请先同意隐私政策',
        icon: 'none',
        duration: 1500
      });
      
      // 跳转到隐私政策页面
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/settings/privacy'
        });
      }, 1500);
      return;
    }
  } catch (e) {
    console.error('获取隐私政策状态失败', e);
    showPrivacyPolicy();
    return;
  }

  loading.value = true;
  try {
    console.log('保存联系人数据...', formData.value);
    
    if (contactId.value) {
      // 更新联系人
      const contactData: Contact = {
        id: contactId.value,
        name: formData.value.name || '',
        category: formData.value.category || '',
        notes: formData.value.notes,
        createTime: '', // 创建时间会在store中处理
        updateTime: ''  // 更新时间会在store中处理
      };
      await contactStore.updateContact(contactData);
    } else {
      // 添加新联系人
      const newContact: Omit<Contact, 'id' | 'createTime' | 'updateTime'> = {
        name: formData.value.name || '',
        category: formData.value.category || '',
        notes: formData.value.notes
      };
      await contactStore.addContact(newContact);
    }
    
    uni.showToast({
      title: '保存成功',
      icon: 'success'
    });
    
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    console.error('保存失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'error'
    });
  } finally {
    loading.value = false;
  }
};

// 生命周期
onMounted(async () => {
  await contactStore.loadContacts();
  
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  // @ts-ignore 忽略$page属性的类型错误
  const options = currentPage.$page?.options || {};
  const id = options.id;
  
  if (id) {
    contactId.value = id;
    const contact = contactStore.getContactById(id);
    if (contact) {
      formData.value = { ...contact };
    }
  }
});
</script>

<style lang="scss">
.container {
  padding: 20rpx;
  min-height: 100vh;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .form-item {
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .input {
      width: 100%;
      height: 80rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }
    
    .textarea {
      width: 100%;
      height: 160rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      padding: 20rpx;
      font-size: 28rpx;
    }
    
    .error-tip {
      color: #ff4d4f;
      font-size: 24rpx;
      margin-top: 8rpx;
    }
  }
}

.privacy-notice {
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  
  .privacy-text {
    font-size: 24rpx;
    color: #666;
    display: block;
    line-height: 1.6;
    margin-bottom: 8rpx;
  }
  
  .privacy-link-wrap {
    display: inline-block;
    padding: 8rpx 0;
  }
  
  .privacy-link {
    font-size: 24rpx;
    color: var(--primary-color, #ff4d4f);
    display: inline-block;
    text-decoration: underline;
    font-weight: bold;
  }
}

.submit-btn {
  margin-top: 40rpx;
  padding: 0 20rpx;
  
  .btn {
    width: 100%;
    height: 88rpx;
    font-size: 32rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    
    &:active {
      opacity: 0.8;
    }
    
    &[disabled] {
      opacity: 0.6;
    }
  }
}

// 主题按钮颜色
.theme-wedding .btn {
  background-color: #FF4D4F;
}

.theme-funeral .btn {
  background-color: #2c3e50;
}

.theme-birthday .btn {
  background-color: #FF4D4F;
}

.theme-graduation .btn {
  background-color: #1890FF;
}

.theme-business .btn {
  background-color: #722ED1;
}

.theme-housewarming .btn {
  background-color: #52C41A;
}

.theme-fullmoon .btn {
  background-color: #F759AB;
}

.theme-other .btn {
  background-color: #13C2C2;
}
</style> 
